package cn.bdqn.mallmgr.service.impl;

import cn.bdqn.mallmgr.dao.ProductImageMapper;
import cn.bdqn.mallmgr.dao.ProductMapper;
import cn.bdqn.mallmgr.dao.PropertyMapper;
import cn.bdqn.mallmgr.dao.ReViewMapper;
import cn.bdqn.mallmgr.pojo.Page;
import cn.bdqn.mallmgr.pojo.Product;
import cn.bdqn.mallmgr.pojo.ProductImage;
import cn.bdqn.mallmgr.service.ProductService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author
 * @create 2022-07-13 10:18
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductImageMapper productImageMapper;

    @Resource
    private PropertyMapper propertyMapper;

    @Resource
    private ReViewMapper reViewMapper;

    /**
     * 商品查询
     *
     * @param categoryId  类别id
     * @param productName 查询商品名称
     * @param sort_key    排序字段
     * @param sort_type   排序规则，0升序1降序
     * @param index       当前页
     * @param size        查询行数
     * @return cn.bdqn.mallmgr.pojo.Page
     */
    @Override
    public Page getPageProducts(Integer categoryId, String productName, String sort_key, Integer sort_type, Integer index, Integer size) {
        Page page = new Page();
        page.setSize(size);
        page.setCount(productMapper.getPageProductsCounts(categoryId, productName));
        page.setIndex(index);
        List<Product> list = productMapper.getPageProducts(categoryId, productName, sort_key, sort_type, (page.getIndex() - 1) * size, size);
        for (int i = 0; i < list.size(); i++) {
            Integer productId = list.get(i).getProductId();
            List<ProductImage> images = productImageMapper.getProductImagesByProductId(productId, 0);
            list.get(i).setProductImages(images);
        }
        page.setList(list);
        return page;
    }

    /**
     * 根据id查询商品详情
     *
     * @param id id
     * @return cn.bdqn.mallmgr.pojo.Product
     */
    @Override
    public Product getProductById(Integer id) {
        Product product = productMapper.getProductById(id);
        product.setProductImages(productImageMapper.getProductImagesByProductId(id, null));
        product.setPropertyList(propertyMapper.getPropertyListByProductId(id));
        product.setReViews(reViewMapper.getReViewsByProductId(id));
        return product;
    }
}
